package test1.service;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import test1.entity.Account;
import test1.mapper.AccountMapper;

/**
 * @author: mornd
 * @dateTime: 2023/5/15 - 20:33
 */
@Slf4j
@Service
public class AccountService3 {

    @Autowired
    private AccountMapper accountMapper;

    @Transactional(rollbackFor = Exception.class)
    public synchronized void transfer(int from, int to, double money) {
        Account account = findById(from);
        log.debug("account：{}", account);
        if(account != null && (account.getBalance() - money >= 0)) {
            accountMapper.update(from, -money);
            accountMapper.update(to, money);
        } else {
            throw new RuntimeException("账户余额不足");
        }
    }

    public Account findById(int no) {
        return accountMapper.getById(no);
    }
}
